package com.example.springboot.controller;

import com.example.springboot.Exception.ServiceException;
import com.example.springboot.common.OBJ;
import com.example.springboot.common.Result;
import com.example.springboot.service.OrdersService;
import com.example.springboot.service.impl.ProductScoreServiceImpl;
import com.example.springboot.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 订单表(Orders)表控制层
 *
 * @author makejava
 * @since 2024-01-13 17:16:25
 */
@RestController
@RequestMapping("/orders")
public class OrdersController {
    /**
     * 服务对象
     */
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private ProductScoreServiceImpl productScoreService;

    @Autowired
    private OrdersProductMapper ordersProductMapper;

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private CartProductMapper cartProductMapper;

    @Autowired
    private ProductMapper productMapper;


    /**
     * 获取所有订单信息
     *
     * @return
     */
    @GetMapping("/selectAll")
    public Result selectAll() {
        return Result.success(ordersService.selectAll());
    }

    /**
     * 根据ID删除
     *
     * @param id
     * @return
     */
    @DeleteMapping("/deleteById/{id}")
    public Result deleteById(@PathVariable Integer id) {
        ordersService.deleteById(id);
        return Result.success("删除成功!");
    }


    /**
     * 条件查询  分页
     *
     * @param currentPage
     * @param pageSize
     * @param number
     * @param username
     * @param storeName
     * @param status
     * @return
     */
    @GetMapping("/selectByManyConditionInpage")
    public Result selectByManyConditionInpage(@RequestParam("currentPage") Integer currentPage,
                                              @RequestParam("pageSize") Integer pageSize,
                                              @RequestParam("number") String number,
                                              @RequestParam("username") String username,
                                              @RequestParam("storeName") String storeName,
                                              @RequestParam("startTime") String startTime,
                                              @RequestParam("endTime") String endTime,
                                              @RequestParam("status") Integer status) {
        return Result.success(ordersService.selectByManyConditionInpage(currentPage, pageSize, number, username, storeName, startTime, endTime, status));
    }

    /**
     * 条件查询  分页
     *
     * @param currentPage
     * @param pageSize
     * @param number
     * @param username
     * @param storeName
     * @return
     */
    @GetMapping("/selectByManyConditionNoStatusInpage")
    public Result selectByManyConditionNoStatusInpage(@RequestParam("currentPage") Integer currentPage,
                                                      @RequestParam("pageSize") Integer pageSize,
                                                      @RequestParam("number") String number,
                                                      @RequestParam("username") String username,
                                                      @RequestParam("storeName") String storeName,
                                                      @RequestParam("startTime") String startTime,
                                                      @RequestParam("endTime") String endTime) {
        return Result.success(ordersService.selectByManyConditionNoStatusInpage(currentPage, pageSize, number, username, startTime, endTime, storeName));
    }

    /**
     * 分页查询
     *
     * @param currentPage
     * @param pageSize
     * @return
     */
    @GetMapping("/selectByPage")
    public Result selectByPage(@RequestParam("currentPage") Integer currentPage,
                               @RequestParam("pageSize") Integer pageSize) {
        return Result.success(ordersService.selectByPage(currentPage, pageSize));
    }


    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PostMapping("/deleteByIds")
    public Result deleteByIds(@RequestBody List<Integer> ids) {
        ordersService.deleteByIds(ids);
        return Result.success("删除成功！");
    }


    /**
     * 店铺详情
     *
     * @param id
     * @return
     */
    @GetMapping("/OrdersInfo")
    public Result OrdersInfo(@RequestParam("id") Integer id) {
        return Result.success(ordersService.selectById(id));
    }


    @PostMapping("/getTotal")
    public Result getTotal() {
        return Result.success(ordersService.getTotal());
    }

    @GetMapping("/loadUserOrders")
    public Result loadUserOrders(@RequestParam("currentPage") Integer currentPage,
                                 @RequestParam("pageSize") Integer pageSize,
                                 @RequestParam("id") Integer id) {
        return Result.success(ordersService.loadUserOrders(currentPage, pageSize, id));
    }

    @GetMapping("/loadStoreOrders")
    public Result loadStoreOrders(@RequestParam("currentPage") Integer currentPage,
                                  @RequestParam("pageSize") Integer pageSize,
                                  @RequestParam("id") Integer id) {
        return Result.success(ordersService.loadStoreOrders(currentPage, pageSize, id));
    }

    @PostMapping("/getStoreTotal")
    public Result getStoreTotal(@RequestParam("id") Integer id) {
        return Result.success(ordersService.getStoreTotal(id));
    }

    @GetMapping("/selectByPageInStore")
    public Result selectByPageInStore(@RequestParam("currentPage") Integer currentPage,
                                      @RequestParam("pageSize") Integer pageSize,
                                      @RequestParam("id") Integer id) {
        return Result.success(ordersService.selectByPageInStore(currentPage, pageSize, id));
    }


    @PostMapping("/getOrdersByUserId")
    public Result getOrdersByUserId(@RequestParam("currentPage") Integer currentPage,
                                    @RequestParam("pageSize") Integer pageSize,
                                    @RequestParam("userId") Integer userId) {
        return Result.success(ordersService.getOrdersByUserId(currentPage, pageSize, userId));
    }


    @PostMapping("/searchByPayStatusAndUserId")
    public Result searchByPayStatusAndUserId(@RequestParam("currentPage") Integer currentPage,
                                             @RequestParam("pageSize") Integer pageSize,
                                             @RequestParam("payStatus") Integer payStatus,
                                             @RequestParam("userId") Integer userId) {
        return Result.success(ordersService.searchByPayStatusAndUserId(currentPage, pageSize, payStatus, userId));
    }

    @PostMapping("/loadOrderByOrderId")
    public Result loadOrderByOrderId(@RequestParam("orderId") Integer orderId) {
        return Result.success(ordersService.loadOrderByOrderId(orderId));
    }


    @PostMapping("/createOrders")
    public Result createOrders(@RequestBody OBJ obj) {

        // 通过token获取用户id
        User currentUser = TokenUtils.getCurrentUser();
        if (currentUser == null) {
            throw new ServiceException("401", "用户未登录");
        }

        if (obj == null) {
            throw new ServiceException("参数不能为空");
        }


        List<Cart> carts = obj.getCarts();
        for (Cart cart : carts) {
            // 获取购物车内商品的id
            Integer productId = cart.getProductId();
            // 获取这个商品的数量
            Integer quantity = cart.getQuantity();

            // 对商品的剩余减少，销量增加，如果商品数量不够则抛异常
            // 先获取这个商品的信息，判断这个商品的剩余量是否满足用户购买的数量
            Product product = productMapper.selectById(productId);
            if (product.getStock().compareTo(BigDecimal.valueOf(quantity)) < 0) {
                // 如果不足够，抛异常
                throw new ServiceException("商品数量不足");
            }
        }

        // 更新用户对该商品的评分为5分
        for (Cart cart : carts) {
            // 获取购物车内商品的id
            Integer productId = cart.getProductId();
            // 获取这个商品的数量
            Integer userId = cart.getUserId();

            // 更新评分表，如果没有则插入一条数据，如果有，则判断是否比1分小，如果小更改为1分，如果大不更改
            ProductScore productScore = new ProductScore();
            productScore.setProductId(Long.valueOf(String.valueOf(productId)));
            productScore.setUserId(Long.valueOf(String.valueOf(userId)));

            // 查询评分表是否有该商品的评分
            ProductScore productScore1 = productScoreService.select(productScore);
            productScore.setScore(5.0f);
            if (productScore1 != null) {
                // 判断是否比5分小
                if (productScore1.getScore() < productScore.getScore()) {
                    productScoreService.update(productScore);
                }
            } else {
                productScoreService.insert(productScore);
            }
        }
        try {
            Orders orders = new Orders();
            orders.setNumber("1140" + System.currentTimeMillis());
            orders.setUserId(currentUser.getId());
            orders.setPayment(obj.getTotalPrice());
            orders.setPaymentType(1);
            orders.setPayStatus(0);
            orders.setStatus(1);
            orders.setCreateTime(new Date());
            // 创建订单
            Orders newOrders = ordersService.addOrders(orders);

            // 获取订单ID
            Integer orderId = newOrders.getId();
            // 绑定订单和商品的关系
            // 获取购物车的集合
            for (Cart cart : carts) {
                Integer id = cart.getId();
                Integer cartId = cart.getId();
                // 获取购物车内商品的id
                Integer productId = cart.getProductId();
                // 获取这个商品的数量
                Integer quantity = cart.getQuantity();

                // 对商品的剩余减少，销量增加，如果商品数量不够则抛异常
                // 先获取这个商品的信息，判断这个商品的剩余量是否满足用户购买的数量
                Product product = productMapper.selectById(productId);
                if (product.getStock().compareTo(BigDecimal.valueOf(quantity)) < 0) {
                    // 如果不足够，抛异常
                    throw new ServiceException("商品数量不足");
                } else {
                    // 销量加购买数量
                    product.setSales(product.getSales().add(BigDecimal.valueOf(quantity)));
                    // 剩余量减购买量
                    product.setStock(product.getStock().subtract(BigDecimal.valueOf(quantity)));
                    // 如果足够则执行handleBuy方法
                    productMapper.handleBuy(product);
                }

                Integer storeId = product.getStoreId();
                // 通过关系表添加数据
                ordersProductMapper.add(orderId, productId, storeId, quantity);
                // 删除购物车中的商品
                // 先删除购物车和商品的关系表
                cartMapper.deleteById(id);
            }
            return Result.success(newOrders.getNumber());
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("创建订单失败");
        }

    }


    @PostMapping("/confirmReceipt")
    public Result confirmReceipt(@RequestParam("id") Integer id) {
        ordersService.confirmReceipt(id);
        return Result.success("收货成功");
    }


    @PostMapping("/send/{id}")
    public Result send(@PathVariable Integer id) {
        ordersService.send(id);
        return Result.success("发货成功！");
    }

    @PostMapping("/selectUserById")
    public Result selectUserById(@RequestParam("id") Integer id) {
        return Result.success(ordersService.selectUserById(id));
    }
}

